<template>
  <div class="ebook" ref="ebook">
    <ebook-header></ebook-header>
    <ebook-title></ebook-title>
    <ebook-reader></ebook-reader>
    <ebook-menu></ebook-menu>
    <ebook-bookmark></ebook-bookmark>
    <ebook-footer></ebook-footer>
  </div>
</template>

<script>
import EbookReader from '@/components/ebook/EbookReader.vue'
import EbookTitle from '@/components/ebook/EbookTitle.vue'
import EbookMenu from '@/components/ebook/EbookMenu.vue'
import EbookHeader from '@/components/ebook/EbookHeader.vue'
import EbookFooter from '@/components/ebook/EbookFooter.vue'
import EbookBookmark from '@/components/ebook/EbookBookmark.vue'
import { getReadTime, saveReadTime } from '@/utils/localStorage.js'
import { ebookMixin } from '@/utils/mixin.js'

export default {
  mixins: [ebookMixin],
  // 组件注册
  components: {
    EbookReader,
    EbookTitle,
    EbookMenu,
    EbookBookmark,
    EbookHeader,
    EbookFooter
  },
  methods: {
    // 开始计算阅读时间
    startLoopReadTime () {
      let readTime = getReadTime(this.fileName)
      // 如果阅读时间不存在，说明是第一次阅读，需要对阅读时间进行初始化
      if (!readTime) {
        readTime = 0
      }
      // 设置定时器
      this.task = setInterval(() => {
        readTime++
        if (readTime % 30 === 0) {
          saveReadTime(this.fileName, readTime)
        }
      }, 1000)
    },
    move (v) {
      this.$refs.ebook.style.top = v + 'px'
    },
    restore () {
      this.$refs.ebook.style.top = 0
      this.$refs.ebook.style.transition = 'all .2s ease-in-out'
      setTimeout(() => {
        this.$refs.ebook.style.transition = ''
      }, 200)
    }
  },
  watch: {
    // watch中，参数为新的值
    offsetY (v) {
      if (!this.menuVisible && this.bookAvailable) {
        if (v > 0) {
          this.move(v)
        } else if (v === 0) {
          this.restore()
        }
      }
    }
  },
  mounted () {
    this.startLoopReadTime()
  },
  beforeDestroy () {
    // 如果定时器任务存在
    if (this.task) {
      clearInterval(this.task) // 终止当前的定时任务
    }
  }
}
</script>

<style lang="scss" scoped rel="stylesheet/scss">
.ebook {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}
</style>
